package com.luom.usercenter.service.impl;

import com.luom.usercenter.common.ErrorCode;
import com.luom.usercenter.exception.BusinessException;
import com.luom.usercenter.mapper.UserMapper;
import com.luom.usercenter.model.User;
import com.luom.usercenter.model.request.UserUpdateRequest;
import com.luom.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.luom.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final String sALT="luom";

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String password, String checkPassword) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,password,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if (password.length()<8||checkPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        //账户不能包含特殊字符
        String vailPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vailPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }
        //密码和校验密码相同
        if (!password.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入密码不相同");
        }
        //账户不能重复
        User newuser=userMapper.getByUserAccount(userAccount);
        if (newuser!=null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }

        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((sALT + password).getBytes());

        //3.插入数据
        User user=new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPassword);
        userMapper.save(user);
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String password, HttpServletRequest request) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,password)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        if (password.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码过短");
        }
        //账户不能包含特殊字符
        String vailPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vailPattern).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }
        //2.加密
        String newPassword = DigestUtils.md5DigestAsHex((sALT + password).getBytes());

        //查询用户是否存在
        User user=userMapper.getByAccountAndPassword(userAccount,newPassword);
        if(user == null) {
            log.info("user login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码错误");
        }
        if (user.getUserStatus()==1){
            throw new BusinessException(ErrorCode.NO_AUTH,"账号不正常,请联系管理员");
        }
        //3.脱敏
        User safeUser=getSafetUser(user);
        //4.记录用户登录状态
        request.getSession().setAttribute(USER_LOGIN_STATE, safeUser);

        return safeUser;

    }

    @Override
    public List<User> searchUsers(String username) {
        return userMapper.searchUsers("%"+username+"%");
    }

    @Override
    public boolean deleteUser(Long id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public List<User> searchAllUsers(String username) {
        List<User> safetUserList=userMapper.searchAllUsername(username);
        safetUserList.stream().map(user -> {
            getSafetUser(user);
            return user;
        }).collect(Collectors.toList());
        return safetUserList;
    }

    @Override
    public User getSafetUser(User user){
        if (user==null)
            return null;
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUsername(user.getUsername());
        safeUser.setUserAccount(user.getUserAccount());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setGender(user.getGender());
        safeUser.setPhone(user.getPhone());
        safeUser.setEmail(user.getEmail());
        safeUser.setUserRole(user.getUserRole());
        safeUser.setCreateTime(user.getCreateTime());
        safeUser.setUserStatus(user.getUserStatus());
        return safeUser;
    }

    @Override
    public User getById(Long id) {
        User user=userMapper.getById(id);
        user=getSafetUser(user);
        return user;
    }

    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public void updateUser(UserUpdateRequest userUpdateRequest) {
        log.info(userUpdateRequest.toString());
        userMapper.updateUser(userUpdateRequest);
    }
}
